package com.kuaimacode.kframework.agent.services.master;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kuaimacode.kframework.agent.services.oplog.SysOpLogService;
import com.kuaimacode.kframework.agent.util.SessionUtil;
import com.kuaimacode.kframework.agent.vo.request.MasterReq;
import com.kuaimacode.kframework.mybatis.mapper.master.UserMasterMapper;
import com.kuaimacode.kframework.mybatis.models.master.MasterMessage;
import com.kuaimacode.kframework.mybatis.models.master.MasterWaitResp;
import com.kuaimacode.kframework.mybatis.models.master.UserMaster;
import com.kuaimacode.kframework.mybatis.models.master.UserMasterData;
import com.kuaimacode.kframework.mybatis.models.sys.SysOpLog;
import com.kuaimacode.kframework.util.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;


/**
 * @author Administrator
 * @date 2019/04/06
 */
@Service
public class MasterService extends ServiceImpl<UserMasterMapper, UserMaster> {

	public static final String PAOTUI = "跑腿";

	public static final String PAOTUIOROTHER = "跑腿/技能";

	public static final String JINENG = "技能";

	@Autowired
	private SysOpLogService opLogService;

	/**
	 *  分页查找所有的数据
	 * @param pageNum 当前页码，从1开始
	 * @param pageSize  一页显示多少行
	 * @return
	 */
	public PageInfo<UserMaster> findAll(MasterReq req, int pageNum, int pageSize) {
		PageHelper.startPage(pageNum, pageSize);
		QueryWrapper<UserMaster> queryWrapper = new QueryWrapper<>();
		if (StringUtils.isNotEmpty(SessionUtil.getAgentId())){
			queryWrapper.eq("agent_id",SessionUtil.getAgentId());
		}else if (StringUtils.isNotEmpty(req.getAuthStatus())){
			queryWrapper.eq("auth_status",req.getAuthStatus());
		}else if (StringUtils.isNotEmpty(req.getMasterName())){
			queryWrapper.like("master_name",req.getMasterName());
		}else if (StringUtils.isNotEmpty(req.getServiceType())){
			queryWrapper.eq("service_type",req.getServiceType());
		}
//			queryWrapper.eq("status", "1");
		List<UserMaster> datas = baseMapper.selectList(queryWrapper);
		return new PageInfo<UserMaster>(datas);
	}

	public PageInfo<UserMasterData> findMasterAll(MasterReq req, int pageNum, int pageSize) {
		PageHelper.startPage(pageNum, pageSize);
//			queryWrapper.eq("status", "1");
		String authStatus = StringUtils.EMPTY;
		String status = StringUtils.EMPTY;
		if (StringUtils.isNotEmpty(req.getAuthStatus())){
			if ("1".equals(req.getAuthStatus())){
//				queryWrapper.eq("auth_status","0");
				authStatus  = "0";
			}
			if ("2".equals(req.getAuthStatus())){
//				queryWrapper.eq("status","1");
				status = "1";
			}
			if ("3".equals(req.getAuthStatus())){
//				queryWrapper.eq("status","2");
				status = "2";
			}
		}
		List<UserMasterData> datas = baseMapper.findAllMaster(SessionUtil.getAgentId(),authStatus,req.getMasterName(),req.getServiceType(),status);
		Date now = new Date();
		if (CollectionUtils.isNotEmpty(datas)){
			datas.forEach(item->{
				Long times = 0L;
				if ("1".equals(item.getLineStatus())){
					String ms = DateUtil.getDateMs(new Date(),item.getOnlineDate()==null?new Date():item.getOnlineDate());
					BigDecimal msB = new BigDecimal(ms).setScale(2,BigDecimal.ROUND_HALF_UP);
					BigDecimal total = msB.add(item.getTotalTimes()).divide(new BigDecimal("60"),2,BigDecimal.ROUND_HALF_UP);
					item.setTotalTimes(total);
				}
				List<SysOpLog> opLogs = opLogService.findSysOpLog(item.getUserId(),DateUtil.dateToString(now,"yyyy-MM-dd"));
				if (CollectionUtils.isEmpty(opLogs)){
					if (StringUtils.equals("1",item.getLineStatus())){
						//在线说明目前未下线过
						String tweenDate = DateUtil.dateToString(now,"yyyy-MM-dd")+" 00:00:00";
						Date tweenDateP = DateUtil.stringtoDate(tweenDate,"yyyy-MM-dd HH:mm:ss");
						item.setCurrentTimes(DateUtil.parseHHMMSS(System.currentTimeMillis()-tweenDateP.getTime()));
					}else{
						//不在线说明今日无在线记录
						item.setCurrentTimes("00:00:00");
					}
				}else{
					Date nowD = new Date();
					String nowStr = DateUtil.dateToString(nowD,"yyyy-MM-dd");
					for (int i = 0; i < opLogs.size(); i++) {
						SysOpLog opLog = opLogs.get(i);
						if (i==0&&StringUtils.equals("下线",opLogs.get(0).getRemark())){
							SysOpLog opLog_0 = opLogs.get(0);

							times+= opLog_0.getCreatedTime().getTime()- DateUtil.stringtoDate(nowStr+" 00:00:00","yyyy-MM-dd HH:mm:ss").getTime();
						}else if (i==opLogs.size()-1&&StringUtils.equals("上线",opLogs.get(opLogs.size()-1).getRemark())){
							SysOpLog opLog_last = opLogs.get(opLogs.size()-1);
							times+=nowD.getTime()-opLog_last.getCreatedTime().getTime();
						}else{
							SysOpLog opHis = opLogs.get(i);
							if (StringUtils.equals("下线",opHis.getRemark())){
								SysOpLog sysOpLog = opLogs.get(i-1);
								times+= opHis.getCreatedTime().getTime()- sysOpLog.getCreatedTime().getTime();
							}
						}
					}
					item.setCurrentTimes(DateUtil.parseHHMMSS(times));
				}
				item.setServiceType(parseServiceType(item.getSkillType()));
			});
		}
		return new PageInfo<UserMasterData>(datas);
	}


	public List<MasterMessage> findAllMasterMessage(MasterReq req,int pageNum,int pageSize){
		PageHelper.startPage(pageNum, pageSize);
		List<MasterMessage> datas = baseMapper.findMasterMessage(req.getUserId(),SessionUtil.getAgentId(),req.getUserId(),req.getMasterName(),req.getAuthStatus(),req.getServiceType());
		return datas;
	}

	public List<MasterMessage> findAllMasterMessage(Long id){
		List<MasterMessage> datas = baseMapper.findMasterMessage(null,null,id,null,null,null);
		return datas;
	}

	/**
	 * 查找所有的数据
	 * @return
	 */
	public List<UserMaster> findAllWait(MasterReq req) {
		QueryWrapper<UserMaster> queryWrapper = new QueryWrapper<>();
		if (StringUtils.isNotEmpty(SessionUtil.getAgentId())){
			queryWrapper.eq("agent_id",SessionUtil.getAgentId());
		}else if (StringUtils.isNotEmpty(req.getAuthStatus())){
			queryWrapper.eq("auth_status",req.getAuthStatus());
		}else if (StringUtils.isNotEmpty(req.getMasterName())){
			queryWrapper.like("master_name",req.getMasterName());
		}else if (StringUtils.isNotEmpty(req.getServiceType())){
			queryWrapper.eq("service_type",req.getServiceType());
		}
		queryWrapper.eq("status",1);//有效
		List<UserMaster> datas = baseMapper.selectList(queryWrapper);
		return datas;
	}

	public List<MasterWaitResp> findWaitMaster(Long userId, String agentId, Long id, String masterName, String authStatus, String serviceType, String status, String masterStatus){
		List<MasterWaitResp> datas = baseMapper.findWaitMaster(userId,agentId,id,masterName,authStatus,serviceType,status,masterStatus);
		return datas;
	}


	/**
	 * 根据userId查找数据
	 * @return
	 */
	public UserMaster findByUserId(Long userId) {
		QueryWrapper<UserMaster> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("user_id",userId);//有效
		UserMaster data = baseMapper.selectOne(queryWrapper);
		return data;
	}

	private String parseServiceType(String serviceType){
		JSONObject object = JSON.parseObject(serviceType);
		String skillDesc = StringUtils.EMPTY;
		String paotui = StringUtils.EMPTY;
		if (object!=null){
			if (object.containsKey("1")){
				paotui = PAOTUI;
				skillDesc = paotui;
			}
			if (object.containsKey("2")&&StringUtils.isNotEmpty(paotui)){
				skillDesc = PAOTUIOROTHER;
			}else if (object.containsKey("2")&&StringUtils.isEmpty(paotui)){
				skillDesc = JINENG;
			}
			if (object.containsKey("3")&&StringUtils.isNotEmpty(paotui)){
				skillDesc = PAOTUIOROTHER;
			}else if (object.containsKey("3")&&StringUtils.isEmpty(paotui)){
				skillDesc = JINENG;
			}
			if (object.containsKey("4")&&StringUtils.isNotEmpty(paotui)){
				skillDesc = PAOTUIOROTHER;
			}else if (object.containsKey("4")&&StringUtils.isEmpty(paotui)){
				skillDesc = JINENG;
			}
		}
		return skillDesc;
	}
}

